const app = getApp();
import {
  commonUserApiError,
  thumbUpload
} from "./server.config";
const md5 = require("../md5");
let questTime = 10; //中断请求的时间，单位s
let reqTime = 0; //终端请求的计时数
let sign = null;
let timestamp = null;
let isHintNoNetwork = false; //是否已经提示无网络，保证一次网络变化内只提示一次

//生成接口请求时间戳
function createTimer() {
  timestamp = Date.parse(new Date()) / 1000;
  return timestamp;
}
//生成接口请求签名
function createSign() {
  if (!app.globalData.loginJson.client_key) return 'null';
  sign = (md5(app.globalData.loginJson.client_key + '_zw_' + timestamp.toString())).toUpperCase();
  return sign;
}

createTimer();
createSign();

/**
 * promise封装request
 * @param {String} url 接口地址
 * @param {Object} param 接口参数
 * @param {String} ctype 编码类型
 * @param {String} method 请求方法
 * @param {String} signature 是否需要验签
 * @param {Function} resolve 成功回调
 * @param {Function} reject 失败回调
 */
let wxReq = (url, param = {}, ctype = true, method = 'POST', signature = true) => new Promise((resolve, reject) => {
  let header = {
    'Accept': 'application/json',
    'content-type': ctype ? 'application/x-www-form-urlencoded' : 'application/json'
  }
  if (signature) {
    //匹配接口：user/login/
    if (!RegExp(/login/).test(url) && !RegExp(/startup/).test(url)) {
      app.globalData.loginJson.access_token && (param.access_token = app.globalData.loginJson.access_token);
    }
    sign ? param.sign = sign : param.sign = createSign();
    app.globalData.loginJson.openid && (param.openid = app.globalData.loginJson.openid);
  }
  param.timestamp = timestamp;
  param.wx_name = app.globalData.wx_name;
  param.checking_version = app.globalData.app_version;
  param.platform = app.globalData.sysInfo.platform;

  if (app.globalData.netWorkStatus.networkType == 'none') {
    wx.showModal({
      content: '当前无网络连接',
      showCancel: false,
      confirmText: '知道了',
    })
    return;
  }
  const requestTask = wx.request({
    url: url,
    data: param,
    header: header,
    method: method,
    success: res => {
      console.log(url + '===>', res)
      let response = res.data;
      if (res.statusCode == 201 || res.statusCode == 200) {
        //身份已变更
        if (response.status && response.status == -10) {
          requestTask.abort() // 中断请求任务
          dealEixt(response.msg);
          return;
        }
        if (typeof response != 'object' && !Array.isArray(response)) {
          wx.showToast({
            title: '服务维护中，请稍后重试',
            icon: 'none',
          })
          acceptError(url, header, JSON.stringify(response), param);
          wx.hideNavigationBarLoading();
          return;
        }
        response.status == 1 ? resolve(res) : reject(res);
      } else {
        wx.hideNavigationBarLoading()
        acceptError(url, header, JSON.stringify(response), param);
        wx.showToast({
          title: '服务维护中，请稍后重试',
          icon: 'none',
          duration: 3000
        })
        reject({
          status: 'error',
          msg: '服务维护中，请稍后重试'
        });
      }
    },
    fail: error => {
      console.warn('[请求失败 error]', error)
      wx.showModal({
        content: error.errMsg || '服务维护中，请稍后重试',
        showCancel: false
      })
      wx.hideNavigationBarLoading()
      reject({
        status: 'error',
        msg: '服务维护中，请稍后重试'
      });
      acceptError(url, header, JSON.stringify(error.data), param);
    }
  })

  //请求开始后，计时30s，未完成请求则中断请求
  // function computTime(){
  //   setTimeout(() => {
  //     if (reqTime >= questTime) {
  //       requestTask.abort() // 中断请求任务
  //       wx.hideLoading();
  //       wx.showToast({
  //         title: '网络似乎有点问题',
  //         icon: 'none'
  //       })
  //     } else {
  //       reqTime++
  //       computTime();
  //     }
  //   }, 1000)
  // }
})

//当前身份已切换，处理重新登录
const dealEixt = (tip) => {
  app.globalData.loginJson.access_token = '';
  wx.setStorageSync('loginJson', app.globalData.loginJson)
  wx.hideLoading();
  wx.showModal({
    content: tip,
    showCancel: false,
    confirmText: '好的',
    success: () => {
      wx.reLaunch({
        url: '/pages/app-modul/index/index',
      })
    }
  })
}

/**
 * 接收错误
 * @param {String} url API地址
 * @param {String} request API请求头
 * @param {String} response API错误返回
 * @param {Object} param 接口参数
 */
function acceptError(url, header, response, param) {
  let obj = {};
  obj.url = url;
  obj.request = JSON.stringify(header);
  obj.response = JSON.stringify(response);
  obj.wxinfo = JSON.stringify({
    wx_version: app.globalData.sysInfo.version,
    sdk_version: app.globalData.sysInfo.SDKVersion,
    app_version: app.globalData.app_version,
    system: app.globalData.sysInfo.system,
    project: app.globalData.wx_name,
  })
  sign ? obj.sign = sign : obj.sign = createSign();
  app.globalData.loginJson.openid ? obj.openid = app.globalData.loginJson.openid : false;
  obj.timestamp = timestamp;
  obj.wx_name = app.globalData.wx_name;
  obj.param = JSON.stringify(param);
  submitRequstErrorLog(obj);
}

//提交错误
function submitRequstErrorLog(obj) {
  wx.request({
    url: commonUserApiError,
    data: obj,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    method: 'POST',
    success: () => {
      // console.log('提交错误日志success返回', res)
    },
    fail: () => {
      // console.log('提交错误日志fail返回', error)
    },
  })
}

/**
 * 图片上传自己服务器
 * @parsm {String} url 上传接口
 * @parsm {Object} param 上传数据
 * @parsm {String} type 文件类型，可不传
 * @parsm {Function} resolve 上传成功回调
 * @parsm {Function} reject 上传失败回调
 */
const serverUploadFile = (imageFile, type = '') => new Promise((resolve, reject) => {
  let upIndex = 0; //上传索引
  let failNum = 0; //上传失败的次数
  let param = {};
  let https_Reg = /^https/;
  const url = thumbUpload;
  sign ? param.sign = sign : param.sign = createSign();
  param.timestamp = timestamp;
  app.globalData.loginJson.access_token ? (param.access_token = app.globalData.loginJson.access_token) : false;
  param.wx_name = app.globalData.wx_name;
  param.type = type;

  const uploadTask = () => new Promise((resolve, reject) => {
    wx.uploadFile({
      url: url,
      filePath: imageFile[upIndex].path,
      name: 'file',
      formData: param,
      success: res => {
        let datas = JSON.parse(res.data);
        if (res.statusCode == 201 || res.statusCode == 200) {
          if (typeof datas != 'object' && !Array.isArray(datas)) {
            wx.showToast({
              title: '服务维护中，请稍后重试',
              icon: 'none',
            })
            acceptError(url, {}, JSON.stringify(datas));
            wx.hideNavigationBarLoading();
            wx.hideLoading();
            return;
          }
          console.log('upload callback', datas)
          resolve(datas.data);
        } else {
          wx.hideNavigationBarLoading();
          wx.hideLoading();
          acceptError(url, {}, JSON.stringify(datas));
          wx.showToast({
            title: '服务维护中，请稍后重试',
            icon: 'none',
            duration: 3000
          })
          reject(datas);
          return;
        }
      },
      fail: res => {
        console.warn('catch=>', res)
        reject(res);
        wx.showModal({
          content: res.errMsg,
          showCancel: false
        })
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        acceptError(url, {}, JSON.stringify(res.data));
      }
    })
  })
  const uploadFoo = () => {
    if (upIndex >= imageFile.length) {
      if (failNum > 0) {
        console.log('图片上传完成，上传有失败文件，', imageFile)
        return;
      }
      resolve(imageFile);
      return;
    }
    if (imageFile[upIndex].path) {
      let suffixArray = imageFile[upIndex].path.split('.');
      let suffix = suffixArray[suffixArray.length - 1].toLowerCase();
      console.log('suffix', suffix)
      if (https_Reg.test(imageFile[upIndex].path)) {
        console.log('无需上传，', imageFile[upIndex].path)
        upIndex++;
        uploadFoo();
      } else {
        uploadTask().then(res => {
          imageFile[upIndex].path = res.url;
          imageFile[upIndex].url = res.url;
          imageFile[upIndex].thumb = res.thumb;

          upIndex++;
          uploadFoo();
        }).catch(res => {
          upIndex++;
          failNum++;
          uploadFoo();
        })
      }
      // //视频上传
      // if (suffix == 'mp4' || suffix == 'mov' || suffix == 'm4v' || suffix == '3gp' || suffix == 'avi' || suffix == 'm3u8' || suffix == 'webm') {
      //   let obj = {
      //     path: imageFile[upIndex].path,
      //     url: imageFile[upIndex].path
      //   }
      //   uploadFile([obj], '', 'other', (video) => {
      //     imageFile[upIndex].path = video[0].path;
      //     upIndex++;
      //     uploadFoo();
      //   }, (res) => {
      //     upIndex++;
      //     failNum++;
      //     uploadFoo();
      //   })
      // }
      // else {

      // }
    } else {
      imageFile[upIndex].path = null;
      upIndex++;
      uploadFoo();
    }
  }
  uploadFoo();
})


module.exports = {
  wxReq,
  serverUploadFile
}